<?php
/**
 * @name /lib/private/TripItem.php
 * @author Kimberly Berger <knb4850@esu.edu>
 * @version 2011.03.30
 *
 * A TripItem class to manage TripItems
 *
 */

/**
 * TripItem class.
 *
 */
ReqLib('/lib/private/Item.php');
ReqLib('/lib/private/Trip.php');

class TripItem {
  /**
   * TripItem identification.
   *
   * @var integer
   */
  var $TripItemId;
  /**
   * TripItem quantity.
   *
   * @var integer
   */
  var $TripQuantity;
   /**
   * TripItem DateDoanted.
   *
   * @var string
   */
  var $DateTransfered;
   /**
   * TripItem's Item Object
   *
   * @var Object
   */
  var $ItemObject;
   /**
  * TripItem's TripObject.
  *
  * @var Object
  */
   var $TripObject;


  /* Methods:

  TripItem()

  "GET":
   TripItems[] GetTripItems(int offset, int maxResults)
   bool Exists(TripItemId)
   string ToString()

  "SCUD":
   bool Load(int TripItemID)
   bool Create(TripId, ItemID)
   bool Save()
   static bool Delete(TripItemId)

  Custom:
	GetTripItemIdByItemId($ItemId)
	GetTripItemIdbyTripId($TripId)
	GetTripItemIdbyTripAndItemId($TripId, $ItemId)

*/

  /**
  *
  * Constructor.
  *
  */
  function TripItem(){
	$this->TripItemId = 0;
    $this->TripQuantity = 0;
	$this->DateTransfered = '';
    $this->ItemObject = new Item();
	$this->TripObject = new Trip();
}

 /**
   * Generates a list of TripItems.
   *
   * @param optional integer offset
   * @param optional integer maxResults
   * @return aray of TripItem Objects
   */
  function GetTripItems($offset =0, $maxResults=0){

  		$objects = array();
		$db = new DB();
		// Initial query
		$query = "SELECT TripItemId FROM tripitems ORDER BY TripItemId";
		// Look for max results and offsets
		if ($maxResults && $maxResults * 1 == $maxResults) {
			$query .= " LIMIT $maxResults";
			if ($offset && $offset * 1 == $offset)
				$query .= " OFFSET $offset";
		}
		elseif ($offset && $offset * 1 == $offset)
			$query .= " LIMIT 99999999 OFFSET $offset";
		// Get the ids
		$ids = $db->QueryCol($query);
		// If we have ids, load the objects
		if (is_array($ids))
		foreach ($ids as $id) {
			$objects[count($objects)] = new TripItem();
			$objects[count($objects) - 1]->Load($id);
		}
		return $objects;
    }

	/**
   * Determines if a tripitem already exists by giving the tripItemId.
   * Returns true if the tripitem exists and false otherwise.
   *
   * @param integer
   * @return boolean
   */
  function Exists($tripItemId){
        $db = new DB();
        return ($db->QueryVal("SELECT TripItemId FROM tripitems WHERE TripItemId='" . addslashes($tripItemId) . "' LIMIT 1;") > 0);
  }

  /**
    * Lists the attributes about a trip item, and returns a string of information
	*
    * @param optional delimiter value
    * @return string
    */
  function ToString($del = "<br />"){

		  $str = "";
		  $str .= 'TripItemId = ' . $this->TripItemId . $del;
		  $str .= 'Quantity = ' . $this->TripQuantity . $del;
		  $str .= 'GoodsTransferDate= ' . $this->DateTransfered . $del;
		  $str .= 'TripId = ' . $this->TripId . $del;
          $str .=  Item::ToString("\r\n") . $del;

		  return $str;

  }

   /**
  *
  * Loads the TripItem information.
  * Returns a true on success; a false on failure
  *
  *  @param integer
  *  @return boolean
  */
  function Load($tripItemId){
	if(!TripItem::Exists($tripItemId))//check to see if the item exists you can't load something that doesn't exist
         return false;
	// Select the TripItemId's attributes and store them
    $db = new DB();
    $data = $db->QueryRow("SELECT TripItemId, TripId, ItemId, Quantity, GoodsTransferDate FROM tripitems Where TripItemId = '" . addslashes($tripItemId) . "';");
        $this->TripItemId = $data["TripItemId"];
        $this->TripQuantity = $data["Quantity"];
        $this->DateTransfered = $data["GoodsTransferDate"];
        $this->ItemObject = Item::Load($data["ItemId"]);
		$this->TripObject = Trip::Load($data["TripId"]);
        return true;
  }

  /**
   * Creates a TripItem
   * returns true on success, false on failure.
   *
   * @param integer
   * @param integer
   * @return boolean
   */
  function Create($tripId, $itemId){
	if(Trip::Exists($tripId) && Item::Exists($itemId)){	//make sure both the trip and item exist
		if (TripItem::Exists(TripItem::GetTripItemIdbyTripAndItemId($tripId, $itemId))) //make sure the item doesn't already exist on the trip
              return false;
		else{ // create a new TripItemId
			$db = new DB();
			$sql = "INSERT INTO tripitems (ItemId, TripId) VALUES ('" . addslashes($itemId) ."', '" . addslashes($tripId). "');";
			$db->Query($sql);
			$sql = "SELECT LAST_INSERT_ID();";
			$this->TripItemId = $db->QueryVal($sql);
			$this->TripId = $tripId;
			$ItemObject = new Item();
			$this->ItemObject->Load($itemId);
			$TripObject = new Trip();
			$this->TripObject->Load($tripId);
			return true;
		}
	  }
	  else //either the trip or the item didn't exist
		return false;
  }
  /**
  * Saves a TripItem
  * returns true on success, false on failure.
  *
  * @return boolean
  */
  function Save(){
    if (!TripItem::Exists($this->TripItemId)) // make sure the TripItem already exists before you save it
		return false;
	else{ // the tripitem exists
		if(Trip::Exists($this->TripId) && Item::Exists($this->ItemId)){ // make sure the trip and item exists incase they were changed
			$db = new DB();
			$data = $db->QueryRow("UPDATE tripitems
                    SET TripId ='" .addslashes($this->TripId). "',
                    ItemId='" . addslashes($this->ItemId) . "',
                    Quantity='" . addslashes($this->TripQuantity) . "',
                    GoodsTransferDate='" . date('Y-m-d', $this->DateTransfered) . "'
                    Where TripItemId='" . addslashes($this->TripItemId) ."';");
			$ItemObject = new Item();
			if(!$this->ItemObject->Load($data["ItemId"]))
				return false;
			$TripObject = new Trip();
			if(!$this->TripObject->Load($data["TripId"]))
				return false;
         return true;
		}
		else
			return false;
    }
  }

  /**
   * Deletes a TripItem using a tripItemId
   * returns true on success, false on failure.
   *
   * @param integer
   * @return boolean
   */
  function Delete($tripItemId){
    if(!TripItem::Exists($tripItemId)) //Don't try to delete a tripitem that doesn't exist
        return false;
    else{
        $db = new DB();
		$db->Query("DELETE FROM tripitems Where TripItemId ='".addslashes($tripItemId)."';");
        return true;
    }
  }

  /**
  * STATIC METHOD
  * Gets the $TripItemId by using the $ItemId.
  * Returns a true on success; a false on failure
  *
  *  @param integer
  *  @return integer
  */
  function GetTripItemIdsByItemId($itemId){
	  $tripItemIds = array(); //create an array
      $db = new DB();
      $tripItemIds = $db->QueryCol("SELECT TripItemId FROM tripitems Where ItemId='" . addslashes($itemId) . "';"); // place the items in the array
      return $tripItemIds;
  }
  /**
  * STATIC METHOD
  * Gets the $TripItemIds by using the $tripId.
  * Returns a string of TripItemIds
  *
  *  @param integer
  *  @return string
  */
  function GetTripItemIdsbyTripId($tripId){
	  $tripItemIds = array(); // create an array
      $db = new DB();
      $tripItemIds = $db->QueryCol("SELECT TripItemId FROM tripitems Where TripId='" . addslashes($tripId) . "';"); //place the items in the array
      return $tripItemIds;
  }
  /**
  * STATIC METHOD
  * Gets the $TripItemIds by using the $tripId and $itemId.
  * Returns an array of TripItemIds
  *
  *  @param integer, @pararm integer
  *  @return integer[]
  */
  function GetTripItemIdbyTripAndItemId($tripId, $itemId){
	  $tripItemIds = array(); // create an array
      $db = new DB();
      $tripItemIds = $db->QueryVal("SELECT TripItemId FROM tripitems Where TripId='" . addslashes($tripId) . "' AND ItemId = '" .addslashes($itemId). "';"); //place the items in the array
      return $tripItemIds;
  }
}
